using System;
using System.Collections;
using UnityEngine;
//using System.Threading;

namespace Pomelo.UnityWebSocketPomelo
{
    public class HeartBeatService
    {
        int interval;
        public int timeout;
        DateTime lastTime;
        Protocol protocol;

        public HeartBeatService(int interval, Protocol protocol)
        {
            this.interval = interval * 1000;
            this.protocol = protocol;
        }

        internal void resetTimeout()
        {
            this.timeout = 0;
            lastTime = DateTime.Now;
        }

        public void sendHeartBeat()
        {
            TimeSpan span = DateTime.Now - lastTime;
            timeout = (int)span.TotalMilliseconds;

            //check timeout
            if (timeout > interval * 2)
            {
                protocol.getPomeloClient().disconnect();
                //stop();
                return;
            }

            //Send heart beat
            protocol.send(PackageType.PKG_HEARTBEAT);
            Debug.Log("heartbeat~");
        }

        public void start()
        {
            if (interval < 1000) return;

            //start hearbeat
            // timer = new Timer();
            // timer.Interval = interval;
            // timer.Elapsed += sendHeartBeat;
            // timer.Enabled = true;
            
            StartTimer(sendHeartBeat);

            //Set timeout
            timeout = 0;
            lastTime = DateTime.Now;

        }

        public void stop()
        {
            // if (this.timer != null)
            // {
            //     this.timer.Enabled = false;
            //     this.timer.Dispose();
            // }
            StopTimer();
        }
        
        private bool timerRunning = false;
        private Coroutine timerCoroutine;
        private Action onTimerExpired;

        public void StartTimer(Action onTimerExpiredCallback)
        {
            onTimerExpired = onTimerExpiredCallback;
            if (!timerRunning)
            {
                timerRunning = true;
                timerCoroutine = protocol.getPomeloClient().GetMb().StartCoroutine(TimerCoroutine());
            }
        }

        public void StopTimer()
        {
            if (timerRunning)
            {
                protocol.getPomeloClient().GetMb().StopCoroutine(timerCoroutine);
                timerRunning = false;
            }
        }

        private IEnumerator TimerCoroutine()
        {
            while (true)
            {
                float timer = 0f;
                while (timer < interval/1000.0f)
                {
                    timer += Time.deltaTime;
                    yield return null; // 等待下一帧
                }

                if (onTimerExpired != null)
                {
                    onTimerExpired();
                }
            }
        }
    }
    
    
    
}